package app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import app.BaseAppV1;
import common.Constant;
import utils.AtguiguUtil;
import utils.FlinkSinkUtil;
import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.util.HashMap;

/**
 * @Author lzc
 * @Date 2022/10/10 08:51
 */
public class Dwd_01_BaseLogApp extends BaseAppV1 {

    private final String START = "start";
    private final String DISPLAY = "display";
    private final String ACTION = "action";
    private final String ERR = "err";
    private final String PAGE = "page";
    private final String VIDEO = "video";

    public static void main(String[] args) throws Exception {
        new Dwd_01_BaseLogApp().init(3001, 2, "Dwd_01_BaseLogApp", Constant.TOPIC_ODS_LOG);
    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        //1.etl
        SingleOutputStreamOperator<JSONObject> etlStream = etl(stream);

        //2.纠正 新老用户
        SingleOutputStreamOperator<JSONObject> correctStream = correctNeworOld(etlStream);

        //3.分流，侧输出流
        HashMap<String, DataStream<JSONObject>> streams = splitStream(correctStream);
//        streams.get(START).print(START);
//        streams.get(DISPLAY).print(DISPLAY);
//        streams.get(ACTION).print(ACTION);
//        streams.get(ERR).print(ERR);
//        streams.get(PAGE).print(PAGE);
//        streams.get(VIDEO).print(VIDEO);

        //4.不同的流 写入 到不同的 Kafka主题中
        writeToKafka(streams);

    }

    //4.不同的流 写入 到不同的 Kafka主题中
    private void writeToKafka(HashMap<String, DataStream<JSONObject>> streams) {
        streams.get(START).map(JSONAware::toJSONString).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_START));
        streams.get(DISPLAY).map(obj -> obj.toJSONString()).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_DISPLAY));
        streams.get(ACTION).map(obj -> obj.toJSONString()).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ACTION));
        streams.get(ERR).map(obj -> obj.toJSONString()).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ERR));
        streams.get(PAGE).map(obj -> obj.toJSONString()).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_PAGE));
        streams.get(VIDEO).map(obj -> obj.toJSONString()).addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_APPVIDEO));
    }

    //3.分流，侧输出流
    private HashMap<String, DataStream<JSONObject>> splitStream(SingleOutputStreamOperator<JSONObject> correctStream) {
        //测输出流
        //主流: 启动
        //侧输出流: 日志 曝光 活动 错误, video
        // 泛型擦除
        OutputTag<JSONObject> displayTag = new OutputTag<JSONObject>("display") {
        };
        OutputTag<JSONObject> actionTag = new OutputTag<JSONObject>("action") {
        };
        OutputTag<JSONObject> errTag = new OutputTag<JSONObject>("err") {
        };
        OutputTag<JSONObject> pageTag = new OutputTag<JSONObject>("page") {
        };
        OutputTag<JSONObject> videoTag = new OutputTag<JSONObject>("video") {
        };

        SingleOutputStreamOperator<JSONObject> Stream = correctStream.process(new ProcessFunction<JSONObject, JSONObject>() {
            @Override
            public void processElement(JSONObject value, Context ctx, Collector<JSONObject> out) throws Exception {


                JSONObject appVideo = value.getJSONObject("appVideo");
                if (appVideo != null) {
                    ctx.output(videoTag, value);
                } else {
                    //1.获取 启动日志start
                    JSONObject start = value.getJSONObject("start");
                    if (start != null) {
                        out.collect(value);
                    } else {
                        //侧输出流
                        //公共信息common
                        JSONObject common = value.getJSONObject("common");
                        JSONObject page = value.getJSONObject("page");

                        //2.曝光  displays
                        JSONArray displays = value.getJSONArray("displays");
                        if (displays != null) {
                            for (int i = 0; i < displays.size(); i++) {
                                //获取displays的子集
                                JSONObject display = displays.getJSONObject(i);
                                //将 common与page 都加入到 display中
                                display.putAll(common);
                                display.putAll(page);
                                display.put("ts", value.getLong("ts"));
                                ctx.output(displayTag, display);
                            }
                            //将数据中的displays部分删除
                            value.remove("displays");
                        }
                        //3.action
                        JSONArray actions = value.getJSONArray("actions");
                        if (actions != null) {
                            for (int i = 0; i < actions.size(); i++) {
                                //获取actions的子集
                                JSONObject action = actions.getJSONObject(i);
                                //将 common与page 都加入到 actions中
                                action.putAll(common);
                                action.putAll(page);
                                action.put("ts", value.getLong("ts"));
                                ctx.output(actionTag, action);
                            }
                            //将数据中的actions部分删除
                            value.remove("actions");
                        }
                        //4.err
                        JSONObject err = value.getJSONObject("err");
                        if (err != null) {
                            ctx.output(errTag, err);
                            value.remove("err");
                        }
                        // 5. page
                        ctx.output(pageTag, value);
                    }
                }
            }
        });


        HashMap<String, DataStream<JSONObject>> streams = new HashMap<>();
        streams.put(START, Stream);
        streams.put(DISPLAY, Stream.getSideOutput(displayTag));
        streams.put(ACTION, Stream.getSideOutput(actionTag));
        streams.put(ERR, Stream.getSideOutput(errTag));
        streams.put(PAGE, Stream.getSideOutput(pageTag));
        streams.put(VIDEO, Stream.getSideOutput(videoTag));

        return streams;
    }

    //2.纠正 新老用户(new 为 1， old 为 0)
    private SingleOutputStreamOperator<JSONObject> correctNeworOld(SingleOutputStreamOperator<JSONObject> etlStream) {
        return etlStream.keyBy(obj -> obj.getJSONObject("common").getString("mid")).map(new RichMapFunction<JSONObject, JSONObject>() {
            //设置用户访问的状态
            private ValueState<String> firstVisitDateState;

            @Override
            public void open(Configuration parameters) throws Exception {
                firstVisitDateState = getRuntimeContext().getState(new ValueStateDescriptor<String>("firstVisit", String.class));
            }

            @Override
            public JSONObject map(JSONObject value) throws Exception {

                String firstVisitDate = firstVisitDateState.value();
                Long ts = value.getLong("ts");
                //将 时间戳ts 转化为 yyyy-MM-dd
                String toDate = AtguiguUtil.toDate(ts);
                //创建 common，有利于更新is_new
                JSONObject common = value.getJSONObject("common");
                String isNew = common.getString("is_new");

                if ("1".equals(isNew)) {
                    if (firstVisitDate == null) {
                        //isNew = 1 与 firstVisitDate = null,表示为新用户
                        // 将toDate 更新到 firstVisitDateState 状态中
                        firstVisitDateState.update(toDate);
                    } else if (!toDate.equals(firstVisitDate)) {
                        //toDate != firstVistDate
                        //表示 日期与 状态不相等，则该用户 不是 新用户
                        common.put("is_new", 0);
                    }
                } else {
                    //表示来的是 老用户， 如果状态为null，将 状态设置成 yesterday
                    if (firstVisitDate == null) {
                        String yesterday = AtguiguUtil.toDate(ts - 24 * 3600 * 1000);
                        firstVisitDateState.update(yesterday);
                    }
                }
                return value;
            }
        });
    }

    //1.对数据进行清洗（将数据纠正为json格式）
    private SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> stream) {
        return stream.filter(new FilterFunction<String>() {
            @Override
            public boolean filter(String value) throws Exception {
                try {
                    JSON.parseObject(value);
                } catch (Exception e) {
                    System.out.println("日志不是json格式" + value);
                    e.printStackTrace();
                    return false;
                }
                return true;
            }
        }).map(JSON::parseObject);
    }
}